package com.byq.mm.abstractx.cluster.server.access;

import com.byq.mm.abstractx.cluster.server.ClientEntry;
import com.byq.mm.abstractx.cluster.server.ClusterServer;
import com.byq.mm.abstractx.cluster.server.ServerIdentifier;
import com.byq.mm.abstractx.cluster.server.SmartServer;
import com.byq.mm.abstractx.engine.CoreEnvironment;
import com.byq.mm.abstractx.protocol.Interaction;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class ClientAccessController implements SmartServer {

	CoreEnvironment env;

	ClusterServer clusterServer;
	
	public ClientAccessController(CoreEnvironment env, ClusterServer cs) {
		super();
		this.env = env;
		this.clusterServer = cs;
		load();
	}
	Map<String, ClientEntry> entrys = new HashMap<String,  ClientEntry>();
	void load(){
		Collection<ClientEntry> es = env.getLiteStore().findClientEntrys(clusterServer.getDevice().getId(), clusterServer.getCluster());
		if(es == null)
			return;
		for(ClientEntry ce : es)
			entrys.put(ce.clientTransport, ce);
		
		
	}
	public List<ClientEntry> getClientEntrys(){
		return new ArrayList<ClientEntry>(entrys.values());
	}
	void update(ClientEntry ce){
		env.getLiteStore().updateClientEntry(clusterServer.getDevice().getId(), clusterServer.getCluster(), ce);
	}
	public boolean isKnownTo(String user) {
		return entrys.get(user) != null;
	}
	public boolean permitted(String user) {
		ClientEntry b =  entrys.get(user);
		return b != null && b.permitted;
	}
	public void permit(String user) {
		ClientEntry b =  entrys.get(user);
		b.permitted = true;
		update(b);

	}
	public void forbid(String user) {
		ClientEntry b =  entrys.get(user);
		b.permitted = false;
		update(b);



	}
	public void toggle(String user) {
		if(permitted(user))
			forbid(user);
		else
			permit(user);
		
	}
	public void accepted(String jid){
		if(this.isKnownTo(jid))
			return;
		ClientEntry e = new ClientEntry();
		e.clientTransport = jid;
		e.permitted = true;
		entrys.put(e.clientTransport, e);
		env.getLiteStore().saveClientEntry(clusterServer.getDevice().getId(), clusterServer.getCluster(), e);
	}
	public Collection<String> getWhileList(){
		return entrys.keySet();
	}
	@Override
	public boolean onCommand(Interaction i, String transport) {
		ClientEntry e = entrys.get(transport.split("/")[0]);
		if(e == null)
			return false;
		if(!e.permitted)
			return false;
		return clusterServer.onCommand(i, transport);
		
	}
	@Override
	public ServerIdentifier getId() {
		// TODO Auto-generated method stub
		return clusterServer.getId();
	}
}
